package cn.uce.common.utils;


import cn.uce.core.cache.redis.RedisClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;

 /**
   * Redis工具类
   * @Author liupan
   * @Description
   * @Date  2020-07-01 15:37
   */
@Component
public class RedisUtils {

	private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);

	@Resource
	private RedisClient uceClient ;

	 /**
	   * 获取字符串
	   * @Author liupan
	   * @Description 
	   * @Date  2020-07-01 15:43
	   */
	public String getString(String key) {
		String value = "";
		Jedis jedis = null;
		try {
			jedis = uceClient.getResource();
			value = jedis.get(key);
		} catch (Exception e) {
			logger.error("从redis获取数据【key=" + key + "】出现异常:" + e);
		} finally {
			if (uceClient != null) {
				uceClient.returnResource(jedis);
			}
		}
		return value;
	}

	 /**
	  * 插入一条String类型的数据 seconds必须要有值并且大于0
	  * @param key
	  * @param value 要插入的值
	  * @param seconds 有效时间单位为秒 ,当seconds
	  * */
	 public void putString(String key,String value,int seconds) {
		 Jedis jedis = null;
		 try {
			 if (StringUtils.isBlank(key)) {
				 return;
			 }
			 jedis = uceClient.getResource();
			 if (seconds > 0) {
				 jedis.setex(key, seconds, value);
			 }
		 } catch (Exception e) {
			 logger.error("redis存储【key=" + key + "】数据出现异常:" + e);
		 } finally {
			 if (uceClient != null) {
				 uceClient.returnResource(jedis);
			 }
		 }
	 }
}
